#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2021 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import sys
import argparse
import gn_common_tools

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from scripts.util.file_utils import read_file, write_json_file  # noqa: E402 E501

_default_subsystem = {"common": "build/common"}

def _check_path_prefix(paths):
    allow_path_prefix = ['vendor', 'device']
    result = list(
        filter(lambda x: x is False,
               map(lambda p: p.split('/')[0] in allow_path_prefix, paths)))
    return len(result) <= 1


def scan(subsystem_config_file, example_subsystem_file, source_root_dir):
    subsystem_infos = _read_config(subsystem_config_file,
                                   example_subsystem_file)
    # add common subsystem info
    subsystem_infos.update(_default_subsystem)

    no_src_subsystem = {}
    _build_configs = {}
    for key, val in subsystem_infos.items():
        _all_build_config_files = []
        if not isinstance(val, list):
            val = [val]
        else:
            if not _check_path_prefix(val):
                raise Exception(
                    "subsystem '{}' path configuration is incorrect.".format(
                        key))
        _info = {'path': val}
        for _path in val:
            _subsystem_path = os.path.join(source_root_dir, _path)
            _build_config_files = _scan_build_file(_subsystem_path)
            _all_build_config_files.extend(_build_config_files)
        if _all_build_config_files:
            _info['build_files'] = _all_build_config_files
            _build_configs[key] = _info
        else:
            no_src_subsystem[key] = val

    scan_result = {
        'source_path': source_root_dir,
        'subsystem': _build_configs,
        'no_src_subsystem': no_src_subsystem
    }
    return scan_result

# def write_json_file(output_file, content, check_changes=False):
def gn_hanle_func(gn_file):
    gc = gn_common_tools.GnCommon()
    # constructor
    template = {'file': gn_file, 'line': -1, 'code block': ""}
    input_content = read_file(gn_file)
    print(input_content)

    with open(gn_file, "r", encoding="utf-8") as f:
        for i in gc.find_paragraph_iter("\"//", "\"", f.read()):
            print(i)

    # write json file
    #write_json_file(, )

def handle_filelist(filelist):
    gc = gn_common_tools.GnCommon()
    gc.scan({filelist}, gn_hanle_func)

def handle_path(path):
    gc = gn_hanle_func.GnCommon()
    gn_set = gc.find_files(path, "BUILD.gn", {}, {})
    handle_filelist(gn_set)

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--filelist', required=False,
            help='filelist \"./foo/BUILD.gn, ./foo1/BUILD.gn\"')
    parser.add_argument('--path', required=False,
            help='check path in once')
    parser.add_argument('--output', required=True)
    args = parser.parse_args()

    if args.filelist:
        handle_filelist(args.filelist)
    elif args.path:
        handle_path(args.path)
    else:
        print("Invalid input")
    return 0

if __name__ == '__main__':
    sys.exit(main())
